import {View, Text} from "@tarojs/components";
import React, {useCallback, useEffect, useRef, useState} from "react";
import {OrderItem} from "@/common/apis/model";
import {orderCancelApi, orderListPageApi} from "@/common/apis/home_datasource";
import LogUtils from "@/utils/log";
import Utils from "@/utils/common";
import {Cell, Divider, Empty, Button, Image} from "@antmjs/vantui";
import {getOrderStatusStyle, OrderStatus} from "@/common/enums";
import RouthPath from "@/common/RouthPath";

import {usePullDownRefresh, useReachBottom} from "@tarojs/taro";
import ShowUtils from "@/utils/show_utils";
import EventUtils from "@/utils/event_utils";
import LocalData from "@/common/local_data";
import NumberUtils from "@/utils/number_utils";


export default function OrderList(pros) {
  const [items, setItems] = useState<OrderItem[]>()
  const isFetching = useRef(false);
  const pageIndex = useRef(LocalData.startPage);
  const hasMore = useRef(true);
  const fetchData = useCallback((isRefresh) => {
    if (isFetching.current) {
      return;
    }
    isFetching.current = true;
    if (isRefresh) {
      pageIndex.current = LocalData.startPage;
    }
    let newHasMore: boolean = true;
    orderListPageApi(pros.item.key, isRefresh, pageIndex.current).then((res) => {
      if (res) {
        newHasMore = res.length >= LocalData.limit;
        if (isRefresh || pageIndex.current === LocalData.startPage) {
          setItems(res)
        } else {
          setItems(prevItems => [...prevItems, ...res]);
        }
      } else {
        newHasMore = false;
      }
      hasMore.current = newHasMore;
      isFetching.current = false;
    })
  }, [pros.item.key, setItems]);

  useEffect(() => {
    setItems(undefined);
    fetchData(true)
    const unsubscribe = EventUtils.on(EventUtils.RefreshOrder, () => {
      pageIndex.current = LocalData.startPage; // 重置页码
      fetchData(true);
    })
    return () => {
      unsubscribe()
    }
  }, [fetchData]);
  usePullDownRefresh(() => {
    fetchData(true)
  })
  useReachBottom(() => {
    if (!hasMore.current || isFetching.current) {
      return;
    }
    pageIndex.current++
    fetchData(false)
  })
  const handleButtons = useCallback((e, item, type) => {
    e.stopPropagation(); // 阻止事件冒泡到父级的 onClick
    if (type === -1) {
      Utils.modal("提示", "确定要取消吗？", true, (ok) => {
        if (ok) {
          orderCancelApi(item.id).then((r) => {
            if (r) {
              Utils.showOkToast("取消成功")
              fetchData(true)
            }
          })
        }
      })
    } else if (type === 0 || type === 1) {
      const url = Utils.getUrlWithObject(RouthPath.orderDetail, {
        id: item.id
      })
      Utils.navigateAndListenToEvent(url, EventUtils.RefreshOrder, () => {
        fetchData(true)
      })
    }
  }, [fetchData]);


  const renderActionButtons = useCallback((item) => {
    let buttons = null;
    let cancelButton = (
      <View>
        {/*<Button style={{marginRight: '10px'}} size='normal' type='info' hairline plain onClick={(e) => {*/}
        {/*  handleButtons(e, item, -1);*/}
        {/*}}*/}
        {/*>*/}
        {/*  取消*/}
        {/*</Button>*/}
      </View>
    )

    // 使用枚举值会更清晰和安全
    if (item.status === OrderStatus.WAIT_CONFIRMATION || item.status === OrderStatus.WAIT_PAYMENT) { // 状态为 2
      const isPay = item.status === OrderStatus.WAIT_PAYMENT;
      const btnText = isPay ? '支付' : '确认';
      buttons = (
        <View>
          {cancelButton}
          <Button size='normal' type='info' onClick={(e) => {
            if (isPay) {
              // handleButtons(e, item, 0);
            } else {
              handleButtons(e, item, 1);
            }
          }}
          >
            {btnText}
          </Button>
        </View>
      );
    } else if (item.status < OrderStatus.FINISHED) {
      buttons = (
        <View>
          {cancelButton}
        </View>
      )
    }
    if (buttons) {
      return (
        <View>
          <View style={{
            display: 'flex',
            flexDirection: 'row',
            margin: '10px',
            boxSizing: 'border-box',
            justifyContent: 'flex-end',
          }}
          >
            {buttons}
          </View>
          <Divider style={{marginTop: '0px'}} /> {/* 如果按钮存在，Divider 可以在按钮之后 */}
        </View>
      );
    }
    return null; // 如果没有匹配的状态，则不渲染按钮区域
  }, [handleButtons]);


  const showTimeOrNum = useCallback((item: OrderItem) => {
    const type = item.machineType
    if (type === LocalData.notTimeId) {
      return `样品数量：${NumberUtils.stringToNumber(item.bookTotalTime)}`
    } else {
      return `预约时间：${ShowUtils.getShowTime(item.bookAllTimes)}`
    }
  }, []);


  return (
    <View style={{backgroundColor: 'white'}}>
      {
        items && !Utils.isEmpty(items) ? <View>
          {
            items.map((item) => {
              const orderStatusInfo = getOrderStatusStyle(item.status)
              return <View key={item.id} onClick={() => {
                const url = Utils.getUrlWithObject(RouthPath.orderDetail, {
                  id: item.id
                })
                Utils.navigateAndListenToEvent(url, EventUtils.RefreshOrder, () => {
                  pageIndex.current = LocalData.startPage; // 重置页码
                  fetchData(false);
                })
                //传入url 和 doAction(data)
              }}
              >
                <Cell renderIcon={<Text style={{fontSize: '14px'}}>订单号：{item.id}</Text>}
                  renderTitle={<Text
                    style={{
                          color: orderStatusInfo.color,
                          textAlign: 'right',
                          fontSize: '14px',
                          width: '100%',
                          display: 'inline-block',
                        }}
                  >{orderStatusInfo.text}</Text>}

                />
                <View style={{display: 'flex', flexDirection: 'row', padding: '10px 20px', boxSizing: 'border-box'}}>
                  <View>
                    <Image src={ShowUtils.getImageUrl(item.projectImage)} style={{width: '150px', height: '150px'}} mode='aspectFill' />
                  </View>
                  <View
                    style={{marginLeft: '10px', display: 'flex', flexDirection: 'column', flex: 1, height: '150px'}}
                  >
                    <Text>机器：{item.machineName}</Text>
                    <View>
                      <Text>项目：{item.projectName}</Text>
                      {/*{item.note ? <Text style={{color: 'gray',fontSize: '12px'}}>{`(${item.note})`}</Text> : null}*/}
                    </View>
                    <Text>{showTimeOrNum(item)}</Text>
                    <View style={{flex: 1, display: 'flex', justifyContent: 'flex-end'}}>
                      <Text style={{
                        fontSize: '16px',
                        color: 'red',
                        textAlign: 'right',
                        marginTop: '10px',
                        alignSelf: 'flex-end'
                      }}
                      >{ShowUtils.getDefaultPrice(item.actualAmount)}</Text>
                      <Text style={{
                        fontSize: '16px',
                        color: 'gray',
                        textAlign: 'right',
                        marginTop: '10px',
                        alignSelf: 'flex-end',
                        textDecoration: 'line-through',
                      }}
                      >{`(${ShowUtils.getDefaultPrice(item.amount)})`}</Text>
                    </View>
                  </View>
                </View>
                <Divider style={{margin: '0px 20px'}} />
                {
                  renderActionButtons(item)
                }
              </View>
            })
          }
        </View> : <Empty description='暂无数据' />
      }
    </View>
  )
}


